#include "ASTM.h"

ASTM::ASTM()
{
}

QString ASTM::recordTypeSymbol(ASTM::RecordType type) const
{
    return recordTypeList.value(type);
}

ASTM::RecordType ASTM::recordType(const QString &symbol) const
{
    RecordType type = Header;

    for(int i = Header; i < Max; i ++) {
        if(symbol == recordTypeList[i]) {
            type = (RecordType)i;
            break;
        }
    }

    return type;
}

QByteArray ASTM::dataToFrame(const QByteArray &date)
{
    QByteArray frame;

    frame += STX;
    if(isNewVersion()) {
        frame += '1';
    }

    frame += date;
    frame += ETX;

    quint8 checksum = 0;
    for(int i = 0; i < frame.size(); i++) {
        checksum += frame[i];
    }

    // 添加检验字节的16进制格式输出
    QString chk = QString("%1").arg(checksum, 2, 16, QLatin1Char('0'));
    frame += chk.toUpper().toUtf8();

    frame += CR;
    frame += LF;

    return frame;
}

QByteArray ASTM::dataFromeFrame(const QByteArray &frame)
{
    if((frame.size() < 7) ||
        ! frame.startsWith(ASTM::STX) ||
        ! frame.endsWith(ASTM::LF)) {
        return frame;
    }

    char head[] = {'H', ASTM::FIELD, '\0'};

    int n = frame.indexOf(head);

    int len = frame.size() - (5 + n);
    return frame.mid(n, len);
}
